<template>
	<view class="page-container">
		<scroll-view scroll-y class="scroll-container">
			<view class="header">
				<image src="/static/images/myBackground.png" class="header-bg"></image>
				<view class="user-info" @tap="handleUserClick">
					<image :src="userData.avatarUrl" mode="aspectFill" class="avatar"></image>
					<view class="username">{{ userData.name }}</view>
				</view>
			</view>

			<view class="content">
				<!-- 我的游戏部分 -->
				<view class="section">
					<view class="section-header">
						<text class="section-title">我的游戏</text>
						<text class="section-more" @tap="goToMyGame">查看全部</text>
					</view>

					<view class="game-list">
						<view class="empty-tip" v-if="userData.name == '点击登录'">
							登录后查看，请先登录~
						</view>
						<view class="empty-tip" v-else-if="myGame.length == 0">
							暂无玩过的游戏
						</view>
						<scroll-view scroll-x class="game-scroll" v-else>
							<view class="game-item" 
								  v-for="(item, index) in myGame" 
								  :key="index"
								  @tap="goToGame" 
								  :data-data="item">
								<image :src="item.kyyGameLogo" class="game-icon"></image>
								<text class="game-name">{{ item.kyyGameAppname }}</text>
							</view>
						</scroll-view>
					</view>
				</view>

				<!-- 功能列表部分 -->
				<view class="section menu-list">
					<view class="menu-item" @tap="goTo3">
						<text>我的发布</text>
						<text class="arrow">></text>
					</view>
					<view class="menu-item" @tap="goTo4">
						<text>我的评论</text>
						<text class="arrow">></text>
					</view>
					<view class="menu-item" @tap="goTo5">
						<text>举报渠道</text>
						<text class="arrow">></text>
					</view>
					<view class="menu-item" @tap="goTo1">
						<text>隐私协议</text>
						<text class="arrow">></text>
					</view>
					<!-- <view class="menu-item" @tap="goTo2">
						<text>授权协议</text>
						<text class="arrow">></text>
					</view> -->
					<view class="menu-item">
						<text>版本号</text>
						<text class="version">V{{ banben }}</text>
					</view>
				</view>

				<!-- 退出登录按钮 -->
				<view class="logout-section" v-if="userData.name !== '点击登录'">
					<view class="logout-btn" @tap="logoutLogin">
						退出登录
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 确认框组件 -->
		<CustomConfirm 
			:visible.sync="showConfirm" 
			title="提示" 
			content="确定要退出登录吗？" 
			@confirm="logout"
			@cancel="showConfirm = false" 
		/>

		<CustomConfirm
			:visible.sync="showLoginConfirm"
			title="温馨提示"
			content="亲，您还没登录，请先登录~"
			@confirm="handleLoginConfirm"
			@cancel="handleLoginCancel"
		/>
	</view>
</template>

<script>
import {
	getGame,
	addClick,
	addOpen,
	getConfig
} from '../../api/getApi';
import {
	getUserInfo
} from '../../api/userApi';
import {
	logout
} from '../../api/loginApi';
import {
	getUserGame
} from '../../api/userGameApi';
import userInfo from '../../store/userInfo';
import globalStore from '../../store/global';
import { updateMyViewTabBarText } from '../../utils/tabBarUtils';
import CustomConfirm from '../../components/CustomConfirm/CustomConfirm.vue';
import loginStatusUtils from '../../utils/loginStatusUtils';

export default {
	components: {

		CustomConfirm // 注册组件
	},
	data() {
		// 创建头像数组
		const randomAvatars = [
			'../../static/images/noAvatar.jpg',
			'../../static/images/noAvatar01.jpg',
			'../../static/images/noAvatar02.jpg'
		];
		const randomIndex = Math.floor(Math.random() * 3);
		
		return {
			myGame: [],
			loginStatus: globalStore.getLoginStype(),
			banben: uni.getStorageSync('banben') ? uni.getStorageSync('banben') : '1.0.0',
			userData: {
				// 修改这里，不要直接从本地存储获取
				avatarUrl: randomAvatars[randomIndex],
				name: '点击登录'
			},
			showConfirm: false,
			showLoginConfirm: false,//登录提示框是否显示
		};
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// 检查token是否存在
		const token = globalStore.getToken();
		if (!token) {
			this.handleTokenExpired();
			return;
		}
		
		// 在页面加载时获取用户数据
		updateMyViewTabBarText();
		this.getUserInfoMethod();
		this.getUserGameMethod();
		getConfig({
			page: 1,
			limit: 10
		}).then((res) => {
			let banben = res.list.find((v) => v.type === 'banben');
			let yinsi = res.list.find((v) => v.type === 'yinsi');
			let shouquan = res.list.find((v) => v.type === 'shouquan');
			if (banben) {
				uni.setStorageSync('banben', banben.text);
			}
			if (yinsi) {
				uni.setStorageSync('yinsi', yinsi.text);
			}
			if (shouquan) {
				uni.setStorageSync('shouquan', shouquan.text);
			}
		});
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {
		
		this.getUserInfoMethod();
		this.getUserGameMethod();
	},
	//获取个人信息

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		// 检查token是否存在
		const token = globalStore.getToken();
		if (!token) {
			this.handleTokenExpired();
			return;
		}
		
		// 验证token有效性
		this.getUserInfoMethod();
		this.getUserGameMethod();
		
		// 更新TabBar文本
		updateMyViewTabBarText();
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() { },
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() { },
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() { },
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() { },
	/**
	 * 用户点击右上角分享
	 */
	// 移除onShareAppMessage方法
	methods: {
		//获取用户个人信息
		getUserInfoMethod() {
			getUserInfo().then(res => {
				console.log('获取个人信息');
				if (res.code == 0) {
					// console.log('获取个人信息',res.data);
					//保存用户信息
					userInfo.setUserInfo(res.data);
					if (res.data.avatarUrl == null) {
						// 随机选择一个头像
						const randomAvatars = [
							'../../static/images/noAvatar.jpg',
							'../../static/images/noAvatar01.jpg',
							'../../static/images/noAvatar02.jpg'
						];
						const randomIndex = Math.floor(Math.random() * 3); // 生成0-2的随机数
						res.data.avatarUrl = randomAvatars[randomIndex];
					}
					//保存用户信息
					userInfo.setUserInfo(res.data);
					this.userData = res.data;

				} else if (res.code === 401 || res.code === 403) { // token过期或无效
					// 清除用户信息
					this.handleTokenExpired();
				}
			}).catch(error => {
				// 处理接口调用失败的情况
				if (error.code === 401 || error.code === 403) {
					this.handleTokenExpired();
				}
				console.error('获取个人信息失败:', error);
			});
		},

		// 添加处理token过期的方法
		handleTokenExpired() {
			// 清除用户数据
			userInfo.clearUserInfo();
			// 删除token值
			globalStore.clearTokenAndLoginType();
			// 清除本地数据
			uni.removeStorageSync('myGame');
			uni.removeStorageSync('userData');
			
			this.myGame = [];
			this.loginStatus = false;
			
			// 随机选择一个头像
			const randomAvatars = [
				'../../static/images/noAvatar.jpg',
				'../../static/images/noAvatar01.jpg',
				'../../static/images/noAvatar02.jpg'
			];
			const randomIndex = Math.floor(Math.random() * 3);
			
			// 重置用户数据
			this.userData = {
				avatarUrl: randomAvatars[randomIndex],
				name: '点击登录'
			};
			
			// 更新TabBar文本
			updateMyViewTabBarText();
			
			// 提示用户重新登录
			uni.showToast({
				title: '未登录~',
				icon: 'none',
				duration: 2000
			});
		},

		//获取我的游戏
		getUserGameMethod() {
			getUserGame().then(res => {
				if (res.code === 0) {
					uni.setStorageSync('myGame', JSON.stringify(res.data.list));
					this.myGame = res.data.list;
				} else if (res.code === 401 || res.code === 403) {
					this.handleTokenExpired();
				}
			}).catch(error => {
				if (error.code === 401 || error.code === 403) {
					this.handleTokenExpired();
				}
				console.error('获取我的游戏失败:', error);
			});
		},




		// 移除getPlus方法


		goToMyGame() {
			//检查登录状态
			if (!loginStatusUtils.checkLoginAndShowConfirm(this)) {
				return;
			}
			/* // 预加载数据
			const myGame = uni.getStorageSync('myGame');
			if (myGame && myGame !== '[]') {
				console.log('获取游戏数据',myGame);
				// 如果有缓存数据，直接跳转
				uni.navigateTo({
					url: '/pages/myGame/myGame'
				});
			} else {
				// 如果没有数据，先获取数据再跳转
				uni.showLoading({
					title: '加载中...'
				});
				console.log('获取游戏数据',myGame);
				this.getUserGameMethod().then(() => {
					uni.hideLoading();
					uni.navigateTo({
						url: '/pages/myGame/myGame'
					});
				}).catch(err => {
					uni.hideLoading();
					console.error('获取游戏数据失败:', err);
					// 仍然跳转，但可能需要在myGame页面显示错误状态
					uni.navigateTo({
						url: '/pages/myGame/myGame'
					});
				});
			} */
			uni.navigateTo({
						url: '/pages/myGame/myGame'
					});
		},

		goToGame(e) {
			// 检查登录状态
			if (!loginStatusUtils.checkLoginAndShowConfirm(this)) {
				return;
			}
			let itemdata = e.currentTarget.dataset.data;
			let loginType = 'app';

			//处于微信端时
			if (itemdata.appid && loginType === 'weixin') {
				uni.navigateToMiniProgram({
					appId: itemdata.appid,
					path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
					envVersion: 'release',
					success: (res) => {
						let myGame = uni.getStorageSync('myGame');
						if (!myGame) {
							myGame = [];
						} else {
							myGame = JSON.parse(myGame).slice(0, 300);
						}
						if (!myGame.find((v) => v.id === itemdata.id)) {
							myGame = [itemdata, ...myGame];
						}
						uni.setStorageSync('myGame', JSON.stringify(myGame));
						this.setData({
							myGame: myGame
						});
						addOpen({
							id: itemdata.id
						});
					}
				});
				addClick({
					id: itemdata.id
				});
			}
			//处于APP端时
			else if (itemdata.id && loginType === 'app') {
				uni.showToast({
					title: `正在为您打开游戏，请稍等~`,
					icon: 'none',
				});

				console.log('itemdata',itemdata);
				//跳进外部浏览器打开微信小游戏
				/* plus.runtime.openURL(itemdata.gameUrl, function(res) {
					console.log(res);
				}); */

				//跳进内嵌浏览器webview打开微信小游戏
				//对ur行编码
				let encodedUrl = encodeURIComponent(itemdata.kyyGameUrl);

				// console.log('encodedUrl',encodedUrl);

				addClick({
					id: itemdata.id
				});
				uni.navigateTo({
					url: `/pages/webview/webview?src=${encodedUrl}&title=${itemdata.appname}`,
				}).then(res => {
					// console.log('跳转成功', res);
					addOpen({
						id: itemdata.id
					});
				}).catch(err => {
					console.error('跳转失败', err);
				});

			}

			else {
				uni.showToast({
					title: `尊敬的大人对对不不起起！此游戏出了点小问题~`,
					icon: 'none'
				});
			}
		},




		goTo1() {
			uni.navigateTo({
				url: '/pages/yinsi/yinsi'
			});
		},

		goTo2() {
			uni.navigateTo({
				url: '/pages/shouquan/shouquan'
			});
		},

		goTo3() {
			uni.navigateTo({
				url: '/pages/myForum/myForum'
			});
		},
		goTo5(){
			uni.showModal({
				title: '个人信息安全投诉、举报渠道',
				content: "请发送投诉或者举报邮件到345728984@qq.com，最迟将会在10个工作日内回复",
				showCancel:false
			});
			// await uni.showModal({
			// 	title:'userInfo',
			// 	content:JSON.stringify(this.bindingStore.userInfo),
			// 	showCancel:true,
			// 	confirmText:"ok"
			// })
		},
		goTo4() {
			uni.navigateTo({
				url: '/pages/myReplay/myReplay'
			});
		},

		handleUserClick() {
			// 如果显示的是"点击登录"，点击时跳转到登录页面
			if (this.userData.name === '点击登录') {
				uni.navigateTo({
					url: '/pages/login/login'  // 替换为你实际的登录页面路径
				});
			}else{
				uni.navigateTo({
					url: '/pages/myinformation/myinformation'  // 替换为你实际的登录页面路径
				});
			}
		},
		logoutLogin() {
			// 显示确认框
			this.showConfirm = true;
		},
		
		logout() {
			// 调用登出 API
			logout().then((res) => {
				if (res.code == 0) {
					uni.showToast({
						title: '退出登录成功',
						icon: 'success',
						duration: 2000
					});
					// 清除用户数据
					userInfo.clearUserInfo();
					//删除token值
					globalStore.clearTokenAndLoginType();
					//清除本地数据
					uni.removeStorageSync('myGame');
					this.myGame=[];
					this.loginStatus=false;
					// 随机选择一个头像
					const randomAvatars = [
						'../../static/images/noAvatar.jpg',
						'../../static/images/noAvatar01.jpg',
						'../../static/images/noAvatar02.jpg'
					];
					const randomIndex = Math.floor(Math.random() * 3);
					
					// 重置用户数据
					this.userData = {
						avatarUrl: randomAvatars[randomIndex],
						name: '点击登录'
					};
					// 更新TabBar文本
					updateMyViewTabBarText();
				} else {
					uni.showToast({
						title: '退出登录失败',
						icon: 'none'
					});
				}
			}).catch(() => {
				uni.showToast({
					title: '退出登录失败',
					icon: 'none'
				});
			});
		},

		//登录提示框确认事件
		handleLoginConfirm() {
			uni.navigateTo({
				// 跳进登录页面
				url: '/pages/login/login'
			});
		},
		//登录提示框取消事件
		handleLoginCancel() {
			this.showLoginConfirm = false;
		}
	}
};
</script>
<style>
/* pages/my/my.wxss */
.page-container {
	height: 100vh;
	background-color: #f5f5f5;
}

.scroll-container {
	height: 100%;
}

.header {
	position: relative;
	height: 400rpx;
}

.header-bg {
	width: 100%;
	height: 100%;
}

.user-info {
	position: absolute;
	bottom: 60rpx;
	left: 0;
	right: 0;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.avatar {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	border: 4rpx solid #fff;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.username {
	margin-top: 20rpx;
	color: #333;
	font-size: 32rpx;
	font-weight: 600;
}

.content {
	padding: 30rpx;
}

.section {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 36rpx;
	font-weight: 700;
	color: #333;
}

.section-more {
	font-size: 28rpx;
	color: var(--Color);
}

.game-list {
	min-height: 200rpx;
}

.game-scroll {
	white-space: nowrap;
}

.game-item {
	display: inline-flex;
	flex-direction: column;
	align-items: center;
	width: 140rpx;
	margin-right: 30rpx;
}

.game-icon {
	width: 100rpx;
	height: 100rpx;
	border-radius: 20rpx;
}

.game-name {
	margin-top: 10rpx;
	font-size: 24rpx;
	color: #333;
	text-align: center;
	width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	white-space: normal;
}

.empty-tip {
	text-align: center;
	color: #999;
	line-height: 200rpx;
}

.menu-list {
	padding: 0 30rpx;
}

.menu-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #eee;
	font-size: 30rpx;
}

.menu-item:last-child {
	border-bottom: none;
}

.arrow {
	color: #999;
	font-size: 32rpx;
}

.version {
	color: #999;
	font-size: 28rpx;
}

.logout-section {
	padding: 60rpx 0;
}

.logout-btn {
	background: var(--Color);
	color: #fff;
	text-align: center;
	padding: 24rpx 0;
	border-radius: 45rpx;
	font-size: 32rpx;
	margin: 0 60rpx;
	box-shadow: 0 6rpx 16rpx rgba(249, 147, 21, 0.2);
}

.logout-btn:active {
	opacity: 0.9;
	transform: scale(0.98);
}
</style>

